package csu.big_article.interceptors;

import csu.big_article.util.JwtUtil;
import csu.big_article.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec;
import java.util.Map;
import java.util.Objects;

@Component
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private StringRedisTemplate template;

    //preHandle方法会在请求到达接口之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{

        String token = request.getHeader("Authorization");
        //这里会直接验证这个token我们不使用if
        try {
            //redis验证Token 通过了才解析map
            Map<String, Object> map = JwtUtil.ParseToken(token);
//            String redis_value = template.opsForValue().get(map.get("username"));
//
//            //如果redis_value == null的判断条件，我们登陆了 username有值 尽管我们token不一样 还是可以使用
//            if(!Objects.equals(redis_value, token)) {
//                //没有这个token抛出异常
//                throw new RuntimeException();
//            }
            ThreadLocalUtil.set(map);
            //放行
            return true;
        }catch (Exception e) {
            //不放行
            response.setStatus(401);
            return false;
        }
        //这里return会return给谁
    }

    //请求结束执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
